<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="44%">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span>{{ vdata.isDetail ? '活动详情' : vdata.isAdd ? '新建活动' : '修改活动' }}</span>
        <a-button v-if="!vdata.isDetail" @click="handleOkFunc(true)">保存草稿</a-button>
      </div>
    </template>
    <div class="container">
      <a-steps progress-dot :current="vdata.currentStep" direction="vertical" style="width: 20%;" @change="handleStepChange">
        <a-step title="基础信息配置" />
        <a-step title="活动规则配置" />
        <a-step title="预约奖品配置" />
      </a-steps>

      <!-- 基础信息配置 -->
      <ActivityBasicInfo
        v-if="vdata.currentStep === 0"
        ref="stepForm0Ref"
        v-model:modelValue="vdata.saveObject"
        :isDetail="vdata.isDetail"
        :payAuthList="vdata.payAuthList"
        :rules="vdata.step0Rules"
      />
      <!-- 活动参与条件配置 -->
      <ActivitySetting v-if="vdata.currentStep === 1" ref="stepForm1Ref" v-model:modelValue="vdata.saveObject['activitySetting']" :isDetail="vdata.isDetail" />
      <!-- 活动奖品配置模块 -->
      <ActivityAwardList v-if="vdata.currentStep === 2" ref="stepForm2Ref" v-model:modelValue="vdata.saveObject['activityAwardList']" :isDetail="vdata.isDetail" :award-config="[{ awardType: '0', awardRemark: 'A', awardMaxNum: 1, awardMinNum: 1, labelName: 'A卡券' },{ awardType: '0', awardRemark: 'B', awardMaxNum: 1, awardMinNum: 1, labelName: 'B卡券' },{ awardType: '1', awardRemark: 'C', awardMaxNum: 1, awardMinNum: 1, labelName: 'C实物' },{ awardType: '1', awardRemark: 'D', awardMaxNum: 1, awardMinNum: 1, labelName: 'D实物' },{ awardType: '1', awardRemark: 'E', awardMaxNum: 1, awardMinNum: 1, labelName: 'E实物' },{ awardType: '1', awardRemark: 'F', awardMaxNum: 1, awardMinNum: 1, labelName: 'F实物' }]" />

      <div class="drawer-btn-center">
        <a-button v-if="vdata.currentStep != 0" style="margin-right:8px" @click="onSteps(-1)">
          <step-backward-outlined />
          上一步
        </a-button>
        <a-button v-if="vdata.currentStep != 2" style="margin-right:8px" @click="onSteps(1)">
          <step-forward-outlined />
          下一步
        </a-button>
        <a-button v-if="vdata.currentStep == 2 && !vdata.isDetail" type="primary" :loading="vdata.btnLoading" @click="handleOkFunc(false)">
          <check-outlined />
          创建
        </a-button>
      </div>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import ActivityBasicInfo from '@/views/activity/activityCreate/components/ActivityBasicInfo.vue'
import ActivitySetting from '@/views/activity/activityCreate/components/ActivitySetting.vue'
import ActivityAwardList from '@/views/activity/activityCreate/components/ActivityAwardList.vue'
import { reactive, defineExpose, getCurrentInstance, watch } from 'vue'
import { req, API_URL_ACTIVITY_DETAILS, $activityAddOrEdit, $uploadPicToGzh } from '@/api/manage'
import dayjs from 'dayjs'

// 获取当前实例
const { proxy }: any = getCurrentInstance()
// 绑定弹窗
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties// 绑定卡券弹窗

const props = defineProps(['callbackFunc'])

// 数据源
const vdata: any = reactive({
  visible: false,
  currentStep: 0,
  saveObject: {}, // 保存的活动对象
  step0Rules: {
    imgUrl: [{ required: false }],
    entryway: [ { required: true, message: '请选择活动入口', trigger: 'blur' } ],
  }
})

/**
 * 切换步骤
 */
 function onSteps(step: number) {
  if (step < 0) {
    vdata.currentStep--
  } else {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validateFields().then(() => {
      vdata.currentStep++
    }).catch(() => {})
  }
}
/**
 * 步骤点击切换 详情页专属
 */
 function handleStepChange(step){
  if(!vdata.isDetail) return // 非详情页不处理
  if(step == vdata.currentStep) return // 相同步数不处理
  vdata.currentStep = step
}

/**
 * 公众号素材上传
 */
 async function handleUploadPic(agentNo, imgUrl) {
  if(!agentNo || !imgUrl) return
  try {
    const res = await $uploadPicToGzh({ agentNo, imgUrl })
    vdata.saveObject.thumbMediaId = res
  } catch (error) {
    vdata.saveObject.thumbMediaId = ''
    vdata.saveObject.imgUrl = ''
  }
}

/**
 * 提交表单 isDraft 是否保存草稿
 */
async function handleOkFunc(isDraft: boolean) {
  // 清理校验
  clearFieldValidate()
  proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validateFields(isDraft ? ['activityName'] : undefined).then(async () => {
    // 处理公众号素材上传-----------------------------------------------------------
    vdata.btnLoading = true
    await handleUploadPic(vdata.saveObject.agentNo, vdata.saveObject.imgUrl)
    const MESSAGE = vdata.isAdd ? '创建活动' : '修改活动'
    const METHOD = vdata.isAdd ? 'POST' : 'PUT'
    const requestData:any = {
      ...JSON.parse(JSON.stringify(vdata.saveObject)),
      entryway: vdata.saveObject.entryway ? vdata.saveObject.entryway.join(',') : '',
      payAuthId: vdata.saveObject.payAuthId ? vdata.saveObject.payAuthId : null,
      activityTemplateNo: vdata.activityTemplateNo,
      state: isDraft ? 0 : 1,
    }
    if(vdata.isAdd){
      requestData.activityNo = `ACNO${dayjs().format('YYYYMMDDHHmmss')}`
    }
    // activitySetting 数据处理--------------------------------------------------------------第二步
    const { activitySetting = {} } = requestData
    if (activitySetting.isOnlyOneTimes === 0 || !activitySetting.onlyOneTimes) {
      activitySetting.onlyOneTimes = 0
    }
    if(activitySetting.periodType === 0 || !activitySetting.periodTimes){
      activitySetting.periodTimes = 0
    }
    if (activitySetting.specialType !== 0 && activitySetting.specialContent) {
      activitySetting.specialContent = activitySetting.specialContent.join(',')
    } else {
      delete activitySetting.specialContent
    }
    if (activitySetting.timeType === 1 && activitySetting.timeStartEnd) {
      activitySetting.timeStart = activitySetting.timeStartEnd[0]
      activitySetting.timeEnd = activitySetting.timeStartEnd[1]
    } else {
      delete activitySetting.timeStart
      delete activitySetting.timeEnd
    }
    if(activitySetting.isFirstJoinScore == 0 || !activitySetting.firstJoinScore){
      activitySetting.firstJoinScore = 0
    }
    if(activitySetting.isEveryJoinScore == 0 || !activitySetting.everyJoinScore){
      activitySetting.everyJoinScore = 0
    }
    $activityAddOrEdit(METHOD, { ...requestData }).then(() => {
      $infoBox.message.success(MESSAGE)
      props.callbackFunc()
      onClose()
    }).finally(() => {
      vdata.btnLoading = false
    })
  }).catch(() => {
    vdata.btnLoading = false
  })
}


/**
* 打开抽屉
* @param activityId 编辑活动ID
* @param record 活动详情
* @param payAuthList 支付授权列表
* @param isDetail 是否为详情页
*/
function show(activityId, { activityTemplateNo, activityCode }, payAuthList, isDetail) {
  vdata.activityTemplateNo = activityTemplateNo
  vdata.activityCode = activityCode
  vdata.payAuthList = payAuthList
  vdata.isAdd = !activityId
  vdata.isDetail = isDetail
  // 清除字段验证
  clearFieldValidate()
  // 数据重置
  vdata.currentStep = 0
  vdata.saveObject = {
    litePath: '/pagesActivity/ACTE002/index',
    litePath2: '/pagesActivity/ACTE002/index',
    payAuthId: null,
    imgUrl:'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/0d7de202-7038-41bc-9fd6-93a50b68b537.png',
    activityImg:'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/0d7de202-7038-41bc-9fd6-93a50b68b537.png',
    isNextView: 0
  }
  if(vdata.isAdd){  // 新增
    vdata.visible = true
  }else{  // 修改
    // 获取活动详情
    req.list(API_URL_ACTIVITY_DETAILS, { activityId, activityTemplateNo }).then((result) => {
      Object.assign(vdata.saveObject,result)
      const { startTime, endTime, entryway, activitySetting = {} } = vdata.saveObject
      const { onlyOneTimes, specialType, specialContent, timeType, timeStart, timeEnd, firstJoinScore, everyJoinScore } = activitySetting
      // 第一步数据处理
      vdata.saveObject.activityTime = (startTime && endTime) ? [startTime, endTime] : []
      vdata.saveObject.entryway = entryway !== '' ? entryway.split(',') : []
      // 第二步数据处理,处理限制条件
      activitySetting.isOnlyOneTimes = onlyOneTimes === 0 ? 0 : 1
      activitySetting.specialContent = (specialType !== 0 && specialContent) ? specialContent.split(',') : []
      activitySetting.timeStartEnd = (timeType === 1 && timeStart && timeEnd) ? [timeStart, timeEnd] : null
      // 第三步数据处理
      activitySetting.isFirstJoinScore = firstJoinScore ? 1 : 0
      activitySetting.isEveryJoinScore = everyJoinScore ? 1 : 0
      vdata.visible = true
    })
  }
}
/**
 * 清除字段验证
 */
function clearFieldValidate(){
  if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
  }
}

/**
* 关闭抽屉
*/
function onClose() {
  vdata.visible = false
}

/**
* 暴露方法
*/
defineExpose({ show })
</script>

<style lang="less" scoped>
.container{
  width: 100%;
  height: 100%;
  display: flex;
  padding-bottom: 30px;
}
:deep(.ant-steps){
  width: 20%;
  flex-shrink: 0
}
</style>